import React, { useEffect, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Upload, message, Image, Modal } from 'antd';

import { uploadFile } from './../../api/upload'
import type { UploadFile, UploadProps } from 'antd';

interface propsType {
    value?: UploadFile[];
    onChange?: (e: string) => void;
    limit: number
}

const UploadComponent = (props: propsType) => {
    const { value, onChange, limit } = props;
    const [fileList, setFileList] = useState<any>([]);

    
    const initFile = () => {
        value && setFileList(value)
    }
    // 图片改变  
    const handleChange: UploadProps['onChange'] = (info) => {
        const { fileList } = info;
        if (info.file.status === "done") {
            const arry:any = fileList.map((file) => ({...file, type: file.type, url: file.response, uid: file.uid }))
            onChange && onChange(arry)
        }
        setFileList(fileList)
    };
    // 图片上传
    const customRequest = ({ file, onSuccess, onError }: any) => {
        uploadFile(file).then(res => {
            if (res.code === 0) {
                onSuccess(res.data, file)
            }
        }).catch(err => {
            onError(err);
        })
    }
    const onRemove = () => {
        return true
    }
    const handlePreview = (file: UploadFile) => {
        // 判断图片类型
        if (file.type && file.type.indexOf("image") !== -1) {
            Modal.info({
                title: '预览',
                content: (
                    <div style={{ display: "flex", justifyContent: "center" }}>
                        <Image src={file.url} preview={false} style={{ width: "100%" }}></Image>
                    </div>
                ),
                width: 800,
            })
            return
        }
        // 判断视频类型
        if (file.type && file.type.indexOf("video") !== -1) {
            Modal.info({
                title: '预览',
                content: (
                    <div style={{ display: "flex", justifyContent: "center" }}>
                        <video style={{ width: "100%" }} src={file.url} controls></video>
                    </div>
                ),
                width: 800,
            })
        }
    }

    useEffect(() => {
        initFile()
    }, [value])
    return (
        <Upload fileList={fileList} maxCount={limit} onPreview={handlePreview} onRemove={onRemove} customRequest={customRequest} onChange={handleChange} listType="picture-card">
            <button style={{ border: 0, background: 'none' }} type="button">
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>点击上传</div>
            </button>
        </Upload>
    )
};

export default UploadComponent;